﻿using GetMan.Core.DB.Entities;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;

namespace GetMan.Core.DB.Services.Collection
{
    /// <summary>
    /// 集合管理
    /// </summary>
    [Export(typeof(INodeService))]
    public class NodeService : BaseService<NodesEntity>, INodeService
    {
        [ImportingConstructor]
        public NodeService(IFreeSql freeSql) : base(freeSql)
        {

        }

        public List<NodesEntity> GetByWorkspaceId(long workSpaceId)
        {
            return _freeSql.Select<NodesEntity>()
                .Where(x => x.WorkSpaceId == workSpaceId)
                .OrderBy(x => x.Sort)
                .ToList();
        }

        public bool DeleteWithChildren(long parentId)
        {
            var nodes = _freeSql.Select<NodesEntity>()
                .Where(a => a.Id == parentId)
                .AsTreeCte()
                .ToList(a => a.Id);
            if (nodes.Any())
            {
                var ret = _freeSql.Delete<NodesEntity>()
                    .Where(x => nodes.Contains(x.Id))
                    .ExecuteAffrows();

                //删除所有包含node的请求信息
                var delReq = _freeSql.Delete<RequestEntity>()
                    .Where(x => nodes.Contains(x.NodeId))
                    .ExecuteAffrows();

                return ret > 0;
            }
            return false;
        }
    }
}